package ncs.common.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;

import javax.imageio.ImageIO;

public class SafeCode {
	private char[]code;
	private int width;
	private int height;
	private Font font;
	public  SafeCode(int width,int height)
	{
		this.width=width;
		this.height=height;
		font=new Font("宋体",Font.ITALIC,25);
		code=new char[]{'A','B','C','D','E','F','G','H','I','J',
				'K','L','M','N','O','P','Q','R','S','T',
				'U','V','W','X','Y','Z','1','2','3','4',
				'5','6','7','8','9','0'};
		
	}
	public InputStream createSecurityCode()
	{
		ByteArrayOutputStream out=new ByteArrayOutputStream();
		BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
		Graphics g=image.getGraphics();
		char []randomCode=new char[4];
		Random rand=new Random();
		int cnt=code.length;
		for(int i=0;i<4;++i)
		{
			randomCode[i]=code[rand.nextInt(cnt)];
		}
		String randStr=new String(randomCode);
	//	session.setAttribute("safecode", randStr);
		g.setColor(new Color(237,247,255));
		g.fillRect(0, 0, width, height);
		g.setColor(new Color(181,184,200));
		g.drawRect(0, 0, width-2, height-1);
		g.setColor(new Color(83,125,25));
		g.setFont(font);
		g.drawString(randStr, 2, height-2);
		try {
			ImageIO.write(image, "jpeg", out);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		ByteArrayInputStream input=new ByteArrayInputStream(out.toByteArray());
		return input;
	}
}
